//
//  ZAQNetworkTool.swift
//  ZAQWBDZT
//
//  Created by 赵安庆 on 16/9/22.
//  Copyright © 2016年 zaq. All rights reserved.
//

import UIKit
import AFNetworking
//定义请求的枚举类型
enum RequestType:Int {
    case GET
    case POST
}
class ZAQNetworkTool: AFHTTPSessionManager {
//建立全局访问点（单利）
   static let sharedTools:ZAQNetworkTool = {
    let tools = ZAQNetworkTool()
    tools.responseSerializer.acceptableContentTypes?.insert("text/html")
    tools.responseSerializer.acceptableContentTypes?.insert("text/plain")

    return tools

    }()
    fileprivate func request(type: RequestType, url: String, params: Any?, callBack: @escaping (Any?, Error?)->()) {

        if  type == .GET{

            get(url, parameters: params, progress: nil, success: { (_, response) in
                callBack(response,nil)
                }, failure: { (_, error) in
                    callBack(nil, error)
            })

        }else {

           post(url, parameters: params, progress: nil, success: { (_, response) in
               callBack(response, nil)
                }, failure: { (_, error) in
                callBack(nil ,error)
         })

        }

        
    }


}
//  MARK: -- 微博首页相关接口
extension ZAQNetworkTool{

    func requestStatuses(accessToken: String,sinceId:Int64, maxId: Int64, callBack: @escaping (Any?, Error?)->()) {


            //准备url
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
            //  准备参数
        let params : [String : Any] = [
                "access_token": accessToken,
                "max_id": maxId,
                "since_id": sinceId

            ]

        request(type: .GET, url: url, params: params, callBack: callBack)

    }



}

//  MARK: -- OAuth登录相关接口
extension ZAQNetworkTool{
    //               根据code获取accesstoken
    func requestAccessToken(code: String, callBack: @escaping (Any?, Error?)->()) {
        //请求地址接口
        let url = "https://api.weibo.com/oauth2/access_token"

        let params = [
            "client_id": WeiboAppKey,
            "client_secret": WeiboAppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WeiboRedirect_Uri

        ]
        //使用封装好的请求
        request(type: .POST, url: url, params: params, callBack: callBack)
    }


}
//  发微博相关接口
extension ZAQNetworkTool {

    func upload(access_token: String, status: String, image: UIImage, callBack: @escaping (Any?, Error?)->()) -> Void {
        //  准备url地址
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        //  准备参数
        let params = [
            "access_token": access_token,
            "status": status
        ]

        //let imageData = UIImagePNGRepresentation(image)!
        //  compressionQuality 质量系数0-1, 质量系数越大表示图片越清晰
        let imageData = UIImageJPEGRepresentation(image, 0.5)!




        //  上传请求接口
        post(url, parameters: params, constructingBodyWith: { (formData) in

            //  withFileData 图片的二进制数据
            //  name 表示服务端获取图片的所需要的参数
            //  fileName 表示图片的文件名字 -> 可以随便写,因为服务的会给我们生成一个唯一的图片名
            //  mimeType 图片的资源
            formData.appendPart(withFileData: imageData, name: "pic", fileName: "test", mimeType: "image/jpeg")
            }, progress: nil, success: { (_, response) in
                callBack(response, nil)
        }) { (_, error) in
            callBack(nil, error)
        }

    }
    //  option + cmd + /
    ///
    ///  发送文字微博接口
    /// - parameter access_token: 令牌
    /// - parameter status:       微博内容
    /// - parameter callBack:     闭包回调
    func update(access_token: String, status: String, callBack: @escaping (Any?, Error?)->()) -> Void {
        //  准备url地址
        let url = "https://api.weibo.com/2/statuses/update.json"
        //  准备参数
        let params = [
            "access_token": access_token,
            "status": status
        ]
        //  执行请求
        request(type: .POST, url: url, params: params, callBack: callBack)

    }
}

//  MARK: -- OAuth登录相关接口
extension ZAQNetworkTool {

    //  通过Accesstoken获取用户信息
    func requestUserInfo(accessToken: String, uid: Int64, callBack: @escaping (Any?, Error?) -> ()) -> Void {
        //  请求接口地址
        let url = "https://api.weibo.com/2/users/show.json"
        //  准备请求需要的参数
        let params: [String: Any] = [
            "access_token": accessToken,
            "uid": uid
        ]

        request(type: .GET, url: url, params: params, callBack: callBack)
        
        
}

}
